package com.haotunet.app.goldtreasure.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.WheelView.OptionsPickerView;
import com.haotunet.app.goldtreasure.WheelView.TimePickerView;
import com.haotunet.app.goldtreasure.db.DBOpenHelper;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.DepositOrder;
import com.haotunet.app.goldtreasure.model.DepositReseverModel;
import com.haotunet.app.goldtreasure.model.Shop;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.net.UrlUtil;
import com.haotunet.app.goldtreasure.other.Interface;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.TimeUtils;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.views.ShopPopupView;
import com.haotunet.app.goldtreasure.views.TitleView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class DepositGoldActivtity extends BaseActivity {
    @InjectView(R.id.title_view)
    TitleView titleView;
    @InjectView(R.id.txt_contact_person)
    TextView txtContactPerson;
    @InjectView(R.id.txt_contact_phone)
    TextView txtContactPhone;
    @InjectView(R.id.tv_county)
    TextView tvCounty;
    @InjectView(R.id.tv_area)
    TextView tvArea;
    @InjectView(R.id.tv_resever_time)
    TextView tvReseverTime;
    @InjectView(R.id.cb_protocal)
    CheckBox cbProtocal;
    @InjectView(R.id.root)
    RelativeLayout root;
    private DBOpenHelper helper;
    private List<Shop> shopList;
    private String reseverTime;
    private String shopId;
    private JSONObject parseShopObject;
    TimePickerView pvTime;
    OptionsPickerView pvOptions;
    private ArrayList<String> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private final int GET_DEPOSIT_RESEVER_PAGE_INFO_SUCCESS = 2;
    private final int SUBMIT_DEPOSIT_RESEVER_INFO_SUCCESS = 3;
    private Handler handle = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_DEPOSIT_RESEVER_PAGE_INFO_SUCCESS:
                    DepositReseverModel model = (DepositReseverModel) msg.obj;
                    String shops = model.getShops();
                    parseShopObject = JSONObject.parseObject(shops);
                    setData(model);
                    initWheelRegionView();
                    break;
                case SUBMIT_DEPOSIT_RESEVER_INFO_SUCCESS:
                    DepositOrder orderModel = (DepositOrder) msg.obj;
                    ActivityUtils.gotoOrderSuccess(DepositGoldActivtity.this, orderModel);
                    DepositGoldActivtity.this.finish();
                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deposit_gold);
        ButterKnife.inject(this);
        helper = new DBOpenHelper(DepositGoldActivtity.this);
        initView();
        initWheelTimeView();
        initData();
    }

    private void initWheelTimeView() {
        pvTime = new TimePickerView(this, TimePickerView.Type.ALL);
        pvTime.setTime(new Date());
        pvTime.setCyclic(false);
        pvTime.setCancelable(true);
        // 时间选择后回调
        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                tvReseverTime.setText(TimeUtils.getTime(date));
            }
        });
    }

    private void initData() {

        ActionUtil actionUtil = new ActionUtil(DepositGoldActivtity.this);
        actionUtil.getAllShopPositionInfo(0);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()){
                    return;
                }
                DepositReseverModel reseverModel = (DepositReseverModel) model;
                if (reseverModel == null) {
                    UIHelper.showToast(DepositGoldActivtity.this, getString(R.string.rank_fail));
                    return;
                }
                if (reseverModel.getErrorMsg() != null) {
                    if (reseverModel.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(DepositGoldActivtity.this, getString(R.string.crowding_in_tips_txt));
                    } else if (reseverModel.getErrorCode().equals(Strs.TOKEN_EXPIRATION)) {
                        ActivityUtils.forceQuit(DepositGoldActivtity.this, getString(R.string.token_expired_tips_txt));
                    } else {
                        UIHelper.showToast(DepositGoldActivtity.this, reseverModel.getErrorMsg());
                    }
                } else {
                    Message msg = new Message();
                    msg.what = GET_DEPOSIT_RESEVER_PAGE_INFO_SUCCESS;
                    msg.obj = reseverModel;
                    handle.sendMessage(msg);
                }
            }
        });
    }

    private void initView() {
        titleView.getTitletextView().setVisibility(View.VISIBLE);
        titleView.getTitletextView().setText(getString(R.string.deposit_reservation));
        titleView.getBackView().setVisibility(View.VISIBLE);
        txtContactPhone.setText(helper.getMobile());
        txtContactPerson.setText(helper.getRealName());
        addCheckBoxListener();
    }

    private void addCheckBoxListener() {
        cbProtocal.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cbProtocal.setChecked(true);
                } else {
                    cbProtocal.setChecked(false);
                }
            }
        });
    }


    private void initWheelRegionView() {
        pvOptions = new OptionsPickerView(this);
        pvOptions.setPicker(options1Items, options2Items, options3Items, true);
        pvOptions.setCyclic(false, false, false);
        // 设置默认选中的三级项目
        // 监听确定选择按钮
        pvOptions.setSelectOptions(0, 0, 0);
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                // 返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1) + options2Items.get(options1).get(option2)
                        + options3Items.get(options1).get(option2).get(options3);
                String region = options3Items.get(options1).get(option2).get(options3);
                tvCounty.setText(tx);
                shopList = JSON.parseArray(parseShopObject.getString(region), Shop.class);
            }
        });
    }

    private void setData(DepositReseverModel reseverModel) {

        List<String> provinces = reseverModel.getProvinces();
        String citys = reseverModel.getCitys();
        String countys = reseverModel.getCountys();
        for (String province : provinces) {
            options1Items.add(province);
            JSONObject parseCityObject = JSONObject.parseObject(citys);
            String string = parseCityObject.getString(province);
            List<String> cityList = JSON.parseArray(string, String.class);
            ArrayList<String> options2Items_01 = new ArrayList<>();
            ArrayList<ArrayList<String>> options3Items_01 = new ArrayList<>();
            for (String city : cityList) {
                options2Items_01.add(city);
                JSONObject parseCountyObject = JSONObject.parseObject(countys);
                String countrys = parseCountyObject.getString(city);
                List<String> countyList = JSON.parseArray(countrys, String.class);
                ArrayList<String> options3Items_01_01 = new ArrayList<>();
                for (String country : countyList) {
                    options3Items_01_01.add(country);
                }
                options3Items_01.add(options3Items_01_01);
            }
            options2Items.add(options2Items_01);
            options3Items.add(options3Items_01);
        }

    }

    private void submitDepositReseverInfo() {
        ActionUtil actionUtil = new ActionUtil(DepositGoldActivtity.this);
        actionUtil.submitDepositReseverInfo(shopId, reseverTime);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()){
                    return;
                }
                DepositOrder orderModel = (DepositOrder) model;
                if (orderModel == null) {
                    UIHelper.showToast(DepositGoldActivtity.this, getString(R.string.rank_fail));
                    return;
                }
                if (orderModel.getErrorMsg() != null) {
                    if (orderModel.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(DepositGoldActivtity.this, getString(R.string.crowding_in_tips_txt));
                    } else if (orderModel.getErrorCode().equals(Strs.TOKEN_EXPIRATION)) {
                        ActivityUtils.forceQuit(DepositGoldActivtity.this, getString(R.string.token_expired_tips_txt));
                    } else {
                        UIHelper.showToast(DepositGoldActivtity.this, orderModel.getErrorMsg());
                    }
                } else {
                    Message msg = new Message();
                    msg.what = SUBMIT_DEPOSIT_RESEVER_INFO_SUCCESS;
                    msg.obj = orderModel;
                    handle.sendMessage(msg);
                }
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.rl_county_layout, R.id.rl_area_layout, R.id.rl_resever_time_layout, R.id.txt_protocol, R.id.btn_submit_order})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_county_layout:
                if (pvOptions!=null) {
                    pvOptions.show();
                }
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_area_layout:
                if (shopList != null && shopList.size() > 0) {
                    ShopPopupView shopView = new ShopPopupView(DepositGoldActivtity.this, DepositGoldActivtity.this,
                            shopList);
                    shopView.showAtLocation(root, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    ActivityUtils.backgroundAlpha(DepositGoldActivtity.this, 0.5f);
                    shopView.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            ActivityUtils.backgroundAlpha(DepositGoldActivtity.this, 1f);
                        }
                    });
                    shopView.setOnShopClickListener(new Interface.OnShopClickListener() {

                        @Override
                        public void onValueSet(Shop shop) {
                            tvArea.setText(shop.getShopName());
                            shopId = shop.getShopID();
                        }
                    });
                } else {
                    tvArea.setText("");
                }
                break;
            case R.id.rl_resever_time_layout:
                pvTime.show();
                break;
            case R.id.txt_protocol:
                ActivityUtils.gotoDynamicDetail(DepositGoldActivtity.this, UrlUtil.LEASE_PROTOCOL, 4);
                break;
            case R.id.btn_submit_order:
                if (!cbProtocal.isChecked()) {
                    UIHelper.showToast(DepositGoldActivtity.this, getString(R.string.please_agree_to_deposit_agreement));
                    return;
                }
                reseverTime = tvReseverTime.getText().toString().trim();
                if (TextUtils.isEmpty(shopId)) {
                    UIHelper.showToast(DepositGoldActivtity.this, "请选择门店");
                    return;
                }
                if (TextUtils.isEmpty(reseverTime)) {
                    UIHelper.showToast(DepositGoldActivtity.this, "请选择预约时间");
                    return;
                }
                submitDepositReseverInfo();
                break;
        }
    }
}
